package com.builder.inputeditor;

import com.swingson.SwingsonGui;
import com.swingson.SwingsonGuiBuilder;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;

public class InputEditorDialog extends JDialog {
    private final SwingsonGui gui;
    private final JTextField fileNamePatternField = new JTextField();
    private final JPanel fieldsTablePanel = new JPanel();
    private final List<InputFieldPanel> allParams = new ArrayList<>();

    public InputEditorDialog(Window owner) {
        setTitle("Input editor");
        gui = SwingsonGuiBuilder.createGuiFromJsonInPackage(this);
        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        ((JScrollPane) (gui.getDefinedComponent("scroll").getComponent())).getVerticalScrollBar().setUnitIncrement(10);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                onClose();
            }
        });

        fieldsTablePanel.setLayout(new MigLayout());
        pack();
    }

    public void removeField(InputFieldPanel field) {
        fieldsTablePanel.remove(field);
        allParams.remove(field);
        revalidate();
        validate();
        repaint();
    }

    public void reorder() {
        ReorderFieldsDialog reorderDialog = new ReorderFieldsDialog(this, allParams);
        if (reorderDialog.showDialog()) {
            List<InputFieldPanel> order = reorderDialog.getOrder();
            fieldsTablePanel.removeAll();
            for (InputFieldPanel panel : order) {
                fieldsTablePanel.add(panel, "width 95%,wrap");
            }

            allParams.clear();
            allParams.addAll(order);
            revalidate();
            validate();
            repaint();
        }
    }

    public void onAddNewField() {
        InputFieldPanel inputFieldPanel = new InputFieldPanel(allParams, this);
        fieldsTablePanel.add(inputFieldPanel, "width 95%,wrap");
        allParams.add(inputFieldPanel);

        revalidate();
        validate();
        repaint();
    }

    private void onClose() {
        setVisible(false);
        dispose();
    }

    private void onSave() {
        setVisible(false);
        dispose();
    }

    private void onCancel() {
        setVisible(false);
        dispose();
    }
}
